package com.hy.z.utils;
import java.io.*;
import java.security.Key;

import javax.crypto.Cipher;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class RSAUtil {
    /** 指定加密算法为RSA */
    private static final String ALGORITHM = "RSA";
    /** 指定公钥存放文件 */
    private static String PUBLIC_KEY_FILE = "PublicKey";
    /** 指定私钥存放文件 */
    private static String PRIVATE_KEY_FILE = "PrivateKey";

    public static void main(String[] args) throws Exception {

        String source = "123456a";// 要加密的字符串
        System.out.println("准备用公钥加密的字符串为：" + source);

        String cryptograph = encrypt(source);// 生成的密文
        System.out.print("用公钥加密后的结果为:" + cryptograph);
        System.out.println();

        String target = decrypt(cryptograph);// 解密密文
        System.out.println("用私钥解密后的字符串为：" + target);
        System.out.println();
    }

    /**
     * 加密方法
     * @param source 源数据
     * @return
     * @throws Exception
     */
    public static String encrypt(String source) throws Exception {

        Key publicKey = getKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHy7k02X0i/l3S5TzqhdLVCEv75UPcsF6fCQj8vDVetuGpcczpyUOyP8pUABK9gqgt6zNzkehCBcheg0/WmVEu9yh5EmUPHLwVnQIHDmeTw0zrzUAlCUJLQcVWNoE6UJDqkayunP1Vwmj+gHVd6pnPvFRV2N+kf1pY58UGvsOSxwIDAQAB\n");

        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(b1);
    }

    /**
     * 解密算法
     * @param cryptograph    密文
     * @return
     * @throws Exception
     */
    public static String decrypt(String cryptograph) throws Exception {

        Key privateKey = getKey("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIfLuTTZfSL+XdLlPOqF0tUIS/vQ9ywXp8JCPy8NV624alxzOnJQ7I/ylQAEr2CqC3rM3OR6EIFyF6DT9aZUS73KHkSZQ8cvBWdAgcOZ5PDTOvNQCUJQktBxVY2gTpQkOqRrK6c/VXCaP6AdV3qmc+8VFXY36R/WljnxQa+w5LHAgMBAAECgYAUxBywbknqngdvBstH+esB1OD5xleYWgg+Pb14GLf4ofLkXJi/b53Almy0Z8Z14JMjYoJdvAROhF/dxCrjYFK/pxwjOiBl+lx+4m2bRZsMpyB9O43Npc1kYvgB7QEk04xUABJz9iUTzv5Xn5lVbWqQPoBC6zcFOqx0h2EX4CNWYQJBAO6O95ycoW1zoRohchYISK/BGDX1jsM71FAawBjY+IUK1bwDkTqET+4uXsgjkeJc/6Y6pTeZepA+pRWGUrCPkfkCQQCRuWAx/84EOshssVVi4bace59g20mZ4nFq1goB/dVEayt0yXPPQ0egx6k5SpFDJEypbJGiF9DlaN12Pu09/Xq/AkEA3TtWpDWZevB1oc8MhyQtjFhNRJUyTRop/hOgvCpS5sayigbg4tybZ643FfHus3c9WoIegB5kTGrcG8cS3kx2uQJAD72NVXlDIJPU6GCzT24AEqEL0yN8rMGX7KlYBWUMr0pANGo6Ny4WQ5itf8G9NRprqXVPucmGx/Du0wHzEFob8wJAOak2mEd4Bmv8EnmMg71OA1V62drQYG4fNNUDL8tmdTIjmcQOxGDRgkQGzTYmEgretWeJeXvA0iK27nDF0O3pQg==");
        System.out.println(privateKey);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b1 = decoder.decodeBuffer(cryptograph);

        /** 执行解密操作 */
        byte[] b = cipher.doFinal(b1);
        return new String(b);
    }

    private static Key getKey(String fileName) throws Exception {
        Key key;
        ObjectInputStream ois = null;
        InputStream byteArrayInputStream = new ByteArrayInputStream(fileName.getBytes());
        try {
            /** 将文件中的私钥对象读出 */
            ois = new ObjectInputStream(byteArrayInputStream);
            key = (Key) ois.readObject();
        } catch (Exception e) {
            throw e;
        } finally {
            //ois.close();
        }
        return key;
    }


}
